package com.lottery.material.aspect;

import com.lottery.material.entity.base.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 数据库save方法为实体类添加创建时间
 * @Author 焦阳
 */
@Component
@Aspect
@Slf4j
public class AddCreateTimeAspect {

    @Pointcut("@annotation(com.lottery.material.aspect.AddCreateTime)")
    public void addPointCut() {

    }

    @Around("addPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Date date = new Date();
        // 设置时间
        this.addCreateTime(point,date);
        //执行方法
        return point.proceed();
    }

    private void addCreateTime(ProceedingJoinPoint point, Date date) throws Exception {
        Object[] args = point.getArgs();
        if (args != null && args.length > 0) {
            if (args[0] instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity)args[0];
                baseEntity.setCreateTime(date);
            }
        }else{
            throw new RuntimeException("参数错误");
        }
    }
}
